package com.hs.jhzd.controller;

import com.hs.jhzd.entity.JhJyzyglEntity;
import com.hs.jhzd.entity.VideoPlay;
import com.hs.jhzd.repository.JhJyzyglRepository;
import com.hs.jhzd.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/v")
@Slf4j
public class VideoPlayController {

  @Autowired
  private JhJyzyglRepository repository;

//  @Value("${video.path}")
//  private String path;
  @Value("${other-file-root-dir-path}")
  private String otherFileRootDirPath;

  @Value("${jsbh}")
  private String jsbh;

  @Value("${jsmc}")
  private String jsmc;
  SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
  @RequestMapping("/admin/main")
  public String main(Model model, @RequestParam(required = true) String jsbh, Pageable pageable) {
    if (StringUtils.isBlank(jsbh) || StringUtils.equals(jsbh, "null")) {
      return "redirect:/v/admin/main?jsbh=" + this.jsbh;
    }
    Page<JhJyzyglEntity> jhJyzyglEntity = repository.findByJsbh(jsbh, pageable);
    for (int i = 0; i <jhJyzyglEntity.getContent().size() ; i++) {
      jhJyzyglEntity.getContent().get(i).setUrl("/acp-cloud"+jhJyzyglEntity.getContent().get(i).getUrl());
      jhJyzyglEntity.getContent().get(i).setTplj("/acp-cloud"+jhJyzyglEntity.getContent().get(i).getTplj());
    }
    model.addAttribute("videoPlays", jhJyzyglEntity);
    model.addAttribute("jsbh", jsbh);
    return "video-list";
  }

  @RequestMapping("/findByJsbh")
  @ResponseBody
  public List<JhJyzyglEntity> findByJsbh(String jsbh, Pageable pageable) {
    if("".equals(jsbh)){
      jsbh=this.jsbh;
    }
    List<JhJyzyglEntity> jhJyzyglEntity = repository.findByJsbhNew(jsbh, pageable);
    for (int i = 0; i <jhJyzyglEntity.size() ; i++) {
      jhJyzyglEntity.get(i).setUrl("/acp-cloud"+jhJyzyglEntity.get(i).getUrl());
      jhJyzyglEntity.get(i).setTplj("/acp-cloud"+jhJyzyglEntity.get(i).getTplj());
    }
    return jhJyzyglEntity;
  }


  @RequestMapping("/findNewVedioByJsbh")
  @ResponseBody
  public List<VideoPlay> findNewVedioByJsbh(String jsbh) throws SQLException, UnsupportedEncodingException {
    if("".equals(jsbh)){
      jsbh=this.jsbh;
    }
    List<VideoPlay> videoPlays = new ArrayList<>();
    List<JhJyzyglEntity> JhJyzyglLists = repository.findTop3ByJsbhAndZyflAndLxOrderBySjcDesc(jsbh,  "1","0");
    for (JhJyzyglEntity jhJyzyglEntity:JhJyzyglLists){
      VideoPlay videoPlay = new VideoPlay();
      videoPlay.setAddress("/acp-cloud"+jhJyzyglEntity.getUrl());
      videoPlay.setCreateTime(jhJyzyglEntity.getSjc());
      videoPlay.setImgUrl("/acp-cloud"+jhJyzyglEntity.getTplj());
      videoPlay.setMc(jhJyzyglEntity.getMc());
      videoPlay.setZyfl(jhJyzyglEntity.getZyfl());
      videoPlay.setJsbh(jhJyzyglEntity.getJsbh());
      videoPlay.setLx(jhJyzyglEntity.getLx());
      if(jhJyzyglEntity.getNr()!=null){
        Blob nr = jhJyzyglEntity.getNr();
        String blobString = new String(nr.getBytes(1, (int) nr.length()),"GBK");
        videoPlay.setNr(blobString);
      }
      videoPlays.add(videoPlay);

    }
    return videoPlays;
  }

  /**
   * location / { root C://Users//lorie//Desktop//; }
   */
  @RequestMapping("/save")
  @ResponseBody
  public boolean save(@RequestParam(required = true) String jsbh,
      @RequestParam(required = true) String name, @RequestParam("video") MultipartFile video,@RequestParam("img") MultipartFile img) throws IOException {
    JhJyzyglEntity videoPlay = new JhJyzyglEntity();
    //生成主键--------
    String oldId = repository.findZybh();
    videoPlay.setZybh(ToolUtils.CreatePrimaryKey(oldId));
    //--------------
    videoPlay.setJsbh(jsbh);
    videoPlay.setJsmc(jsmc);
    videoPlay.setZyfl("1");
    videoPlay.setMc(name);
    videoPlay.setLx("0");
    videoPlay.setScbj(false);
    String dirFilePath = otherFileRootDirPath + File.separator;

    if (!video.isEmpty()) {
      String vpath = getVpath();
      String imgpath = getVpath();
      File vFile = new File(dirFilePath + File.separator + vpath);
      if (!vFile.exists() && !vFile.isDirectory()) {
        vFile.mkdirs();
      }
      vpath += Calendar.getInstance().getTime().getTime() + "." + video.getOriginalFilename();

      File imgfolder = new File(dirFilePath + File.separator +imgpath);
      if (!imgfolder.exists() && !imgfolder.isDirectory()) {
        imgfolder.mkdirs();
      }
      imgpath += Calendar.getInstance().getTime().getTime() + "." + img.getOriginalFilename();

      BufferedOutputStream stream=null;
      BufferedOutputStream stream1=null;
      try {
        stream = new BufferedOutputStream(new FileOutputStream(new File(this.otherFileRootDirPath + vpath)));
        storeVideo(stream, video);
        stream1 = new BufferedOutputStream(new FileOutputStream(new File(this.otherFileRootDirPath + imgpath)));
        storeVideo(stream1, img);
        videoPlay.setUrl("/other/file"+vpath);
        videoPlay.setSjc(new Date());
        videoPlay.setTplj("/other/file"+imgpath);
        repository.save(videoPlay);
        return true;
      } catch (FileNotFoundException e) {
        log.error(e.getMessage());
      }finally {
        if(stream!=null){
          try {
            stream.close();
          } catch (IOException e) {
            log.error("文件流关闭异常");
          }
        }
        if(stream1!=null){
          try {
            stream1.close();
          } catch (IOException e) {
            log.error("文件流关闭异常");
          }
        }
      }
    }
    return false;
  }


  /**
   * 获取目录
   * @return
   */
  private String getDir() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    return sdf.format(new Date());
  }


  private void storeVideo(BufferedOutputStream stream, MultipartFile video) {
    try {
      stream.write(video.getBytes());
    } catch (IOException e) {
      log.error(e.getMessage());
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          log.error(e.getMessage());
        }
      }
    }
  }

  private String getVpath() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
//    return "/other/file/jtjywj/video/" + sdf.format(new Date()) + "/" ;
    return "/jtjywj/" + sdf.format(new Date()) + "/" ;

  }



  @RequestMapping("/del")
  @ResponseBody
  public boolean del(String  id) {
    repository.deleteById(id);
    return true;
  }

}
